package com.eshop.controller;

import com.eshop.pojo.AdminInfo;
import com.eshop.pojo.Functions;
import com.eshop.pojo.TreeNode;
import com.eshop.service.AdminInfoService;
import com.eshop.util.JsonFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

@Controller
@RequestMapping("/admin")
@SessionAttributes(value = {"admin"})
public class AdminInfoController {
    @Autowired
    private AdminInfoService service;

    @RequestMapping(value = "/login",produces = "text/html;charset=UTF-8")
    @ResponseBody//将返回类型转换成json类型
    public String login(Model model, AdminInfo adminInfo){  //登录
        //后台登录验证
        AdminInfo adminInfo1 = service.selectByNameAndPwd(adminInfo);
        if (adminInfo1 != null && adminInfo1.getName() != null){
            //登录验证通过后，进行权限验证
            if ( service.selectById(adminInfo1.getId()).getFunctions().size() > 0 ){
                //权限验证通过后，将管理员对象存入model
                model.addAttribute("admin",adminInfo1);
                //以JSON格式向前端页面发送成功信息
                return "{\"success\":\"true\",\"message\":\"登录成功\"}";
            }else
                return "{\"success\":\"false\",\"message\":\"您没有登录权限，请联系超级管理员设置权限！\"}";
        }else
            return "{\"success\":\"false\",\"message\":\"登录失败！\"}";
    }

    @RequestMapping("/getTree")
    @ResponseBody//将返回类型转换成json类型
    public List<TreeNode> getTree(@RequestParam("adminId") Integer adminId){  //获取TreeData
        //System.out.println("----------------"+adminId+"----------------");
        //根据管理员编号获取管理员
        AdminInfo adminInfo = service.selectById(adminId);
        List<TreeNode> nodes = new ArrayList<>();
        List<Functions> functions = adminInfo.getFunctions();//获取管理员功能权限
        Collections.sort(functions);//将功能按id大小进行排序
        //将排序后的功能对象 转换到 Tree Nodes
        for (Functions f : functions){
            TreeNode treeNode = new TreeNode();
            treeNode.setId(f.getId());//设置节点id
            treeNode.setFid(f.getParentid());//设置父节点id
            treeNode.setText(f.getName());//设置节点名称
            nodes.add(treeNode);//向树中增加一个节点
        }
        //调用自定义工具类的方法buildTree()，设置节点的孩子
        return JsonFactory.buildTree(nodes,0);
    }

    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    public String logout(SessionStatus sessionStatus){
        sessionStatus.setComplete();//清除 SessionAttributes
        //return "{\"success\":\"true\",\"message\":\"注销成功！\"}";
        return "redirect:/admin_login.jsp";
    }
}
